package com.novel.system.service.impl;

import com.novel.common.constants.UserConstants;
import com.novel.common.exception.business.BusinessException;
import com.novel.common.utils.StringUtils;
import com.novel.framework.shiro.utils.MD5Utils;
import com.novel.system.domain.SysUser;
import com.novel.system.domain.SysUserPost;
import com.novel.system.domain.SysUserRole;
import com.novel.system.mapper.SysUserMapper;
import com.novel.system.mapper.SysUserPostMapper;
import com.novel.system.mapper.SysUserRoleMapper;
import com.novel.system.service.SysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户 业务层处理
 *
 * @author novel
 * @date 2019/5/8
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    private final SysUserMapper userMapper;
    private final SysUserRoleMapper sysUserRoleMapper;
    private final SysUserPostMapper userPostMapper;

    public SysUserServiceImpl(SysUserMapper userMapper, SysUserRoleMapper sysUserRoleMapper, SysUserPostMapper userPostMapper) {
        this.userMapper = userMapper;
        this.sysUserRoleMapper = sysUserRoleMapper;
        this.userPostMapper = userPostMapper;
    }

    @Override
    public SysUser findUserByUserName(String username) {
        return userMapper.findUserByUserName(username);
    }

    @Override
    public SysUser login(String username, String password) {
        SysUser user = userMapper.findUserByUserName(username);
        if (user == null) {
            throw new BusinessException("登录失败，用户不存在！");
        }
        return MD5Utils.matches(user, password) ? user : null;
    }

    @Override
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean updateUser(SysUser user) {
        //重新给定权限
        sysUserRoleMapper.deleteUserRoleByUserId(user.getId());
        batchUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(user.getId());
        // 新增用户与岗位管理
        batchUserPost(user);
        return userMapper.updateUser(user) > 0;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean updateUserLoginInfo(SysUser user) {
        return userMapper.updateUser(user) > 0;
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    private boolean batchUserPost(SysUser user) {
        int rows = 1;
        // 新增用户与岗位管理
        List<SysUserPost> list = new ArrayList<>();

        if (user.getPostIds() != null && user.getPostIds().size() > 0) {
            user.getPostIds().forEach(postId -> {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getId());
                up.setPostId(postId);
                list.add(up);
            });

            if (list.size() > 0) {
                rows = userPostMapper.batchUserPost(list);
            }
        }
        return rows > 0;
    }

    private boolean batchUserRole(SysUser user) {
        int rows = 1;
        List<SysUserRole> list = new ArrayList<>();
        if (user.getRoleIds() != null && user.getRoleIds().size() > 0) {
            user.getRoleIds().forEach(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(user.getId());
                list.add(userRole);
            });
        }
        if (list.size() > 0) {
            rows = sysUserRoleMapper.batchUserRole(list);
        }
        return rows > 0;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean insertUser(SysUser user) {
        user.setSalt(MD5Utils.randomSalt());
        user.setPassword(MD5Utils.encryptPassword(user.getUserName(), user.getPassword(), user.getSalt()));
        return userMapper.insertUser(user) > 0 && batchUserRole(user) && batchUserPost(user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean insertUser(List<SysUser> userList) {
        for (SysUser sysUser : userList) {
            insertUser(sysUser);
        }
        return true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean deleteUserById(Long id) {
        return true;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean deleteUserByIds(Long[] ids) {
        for (Long userId : ids) {
            if (SysUser.isAdmin(userId)) {
                throw new BusinessException("不允许删除超级管理员用户");
            }
        }
        return userMapper.deleteUserByIds(ids) > 0;
    }

    @Override
    public SysUser selectUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public SysUser selectUserByIdAndDept(Long id) {
        return userMapper.selectUserByIdAndDept(id);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean updateUserInfo(SysUser user) {
        return userMapper.updateUser(user) > 0;
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean modifyPassword(SysUser user, String oldPassWord, String newPassword) {
        if (MD5Utils.matches(user, oldPassWord)) {//验证旧密码是否正确
            user.setSalt(MD5Utils.randomSalt());
            user.setPassword(MD5Utils.encryptPassword(user.getUserName(), newPassword, user.getSalt()));
            return updateUserInfo(user);
        }
        throw new BusinessException("旧密码不正确！");
    }

    @Override
    public boolean resetUserPwd(Long userId, String newPassword) {
        SysUser user = userMapper.selectUserById(userId);
        user.setSalt(MD5Utils.randomSalt());
        user.setPassword(MD5Utils.encryptPassword(user.getUserName(), newPassword, user.getSalt()));
        return updateUserInfo(user);
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(SysUser user) {
        long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        List<SysUser> userList = userMapper.checkUserNameUnique(user.getUserName());
        if (userList != null) {
            for (SysUser sysUser : userList) {
                if (StringUtils.isNotNull(sysUser) && sysUser.getId() != userId) {
                    return UserConstants.USER_PHONE_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user) {
        long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        List<SysUser> userList = userMapper.checkPhoneUnique(user.getPhoneNumber());
        if (userList != null) {
            for (SysUser sysUser : userList) {
                if (StringUtils.isNotNull(sysUser) && sysUser.getId() != userId) {
                    return UserConstants.USER_PHONE_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user) {
        long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        List<SysUser> userList = userMapper.checkEmailUnique(user.getEmail());
        if (userList != null) {
            for (SysUser sysUser : userList) {
                if (StringUtils.isNotNull(sysUser) && sysUser.getId() != userId) {
                    return UserConstants.USER_EMAIL_NOT_UNIQUE;
                }
            }
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }
}
